<template>
  <view class="container">
    <!-- 首页顶部导航栏 -->
    <view class="header">
      <text class="title">首页概览</text>
    </view>

    <!-- 经营数据概览卡片 -->
    <view class="overview-card-list">
      <view class="overview-card">
        <view class="overview-label">今日订单</view>
        <view class="overview-value">{{ overviewData.todayOrderCount }}</view>
      </view>
      <view class="overview-card">
        <view class="overview-label">营业额</view>
        <view class="overview-value">¥{{ overviewData.todayRevenue }}</view>
      </view>
      <view class="overview-card">
        <view class="overview-label">待处理订单</view>
        <view class="overview-value">{{ overviewData.pendingOrderCount }}</view>
      </view>
    </view>

    <!-- 公告区域 -->
    <view v-if="noticeList.length > 0" class="card section">
      <view class="section-header">
        <text class="section-title">📢 系统公告</text>
      </view>
      <view class="notice-list">
        <view 
          v-for="notice in noticeList" 
          :key="notice.id" 
          class="notice-item"
          @click="navigateToNoticeDetail(notice.id)"
        >
          <text class="notice-title">{{ notice.title }}</text>
          <text class="notice-time">{{ formatNoticeTime(notice.createTime) }}</text>
        </view>
      </view>
    </view>

    <!-- 营业状态卡片 -->
    <view class="card section">
      <view class="section-header status-row">
        <text class="section-title">营业状态</text>
        <switch :checked="shopStatus.checked" @change="toggleShopStatus" />
      </view>
    </view>

    <!-- 快捷功能入口卡片，仅保留必要功能 -->
    <view class="function-row">
      <view class="card function-card">
        <view class="function-item">
          <view class="function-item-inner" @click="navigateToBusinessHours">
            <image class="function-icon" src="/static/icons/time-setting.png"></image>
            <text class="function-text">营业时间设置</text>
          </view>
        </view>
      </view>
      <view class="card function-card">
        <view class="function-item">
          <view class="function-item-inner" @click="navigateToDataAnalysis">
            <image class="function-icon" src="/static/icons/data-analysis.png"></image>
            <text class="function-text">经营数据</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import {getMerchantId} from '@/utils/merchant.js';
import { getMerchantInfo } from '@/api/merchant';
import { updateMerchantStatus } from '@/api/merchant';
import { getMerchantOverviewData } from '@/api/merchant';
import { getNoticeList } from '@/api/notice';


const shopInfo = ref({});
const shopStatus = ref({ checked: false });
const overviewData = ref({
  todayOrderCount: 0,
  todayRevenue: 0,
  pendingOrderCount: 0
});
const noticeList = ref([]);

const toggleShopStatus = async (e) => {
  const merchantId = getMerchantId();
  if (!merchantId) {
    uni.showToast({ title: '未获取到商家ID', icon: 'none' });
    return;
  }
  
  const value = e.detail.value;
  const newStatus = value ? 1 : 0;
  
  // 先更新switch状态
  shopStatus.value.checked = value;
  
  if (value) {
    // 开启营业，直接执行
    try {
      await updateMerchantStatus({ id: merchantId, status: newStatus });
      shopInfo.value.status = newStatus;
      uni.showToast({
        title: '已开始营业',
        icon: 'none'
      });
    } catch (err) {
      // 失败时恢复switch状态
      shopStatus.value.checked = false;
      uni.showToast({ title: err.data.message || '状态更新失败', icon: 'none' });
    }
  } else {
    // 关闭营业，需要二次确认
    uni.showModal({
      content: '您确定要暂停营业吗？',
      confirmText: "取消",
      cancelText: "确定暂停",
      confirmColor: '#cbcbcb',
      cancelColor: '#ff4757',
      success: async function (res) {
        if (res.confirm) {
          // 用户点击取消，恢复switch状态为开启
          shopStatus.value.checked = true;
        } else if (res.cancel) {
          // 用户确认暂停营业
          try {
            await updateMerchantStatus({ id: merchantId, status: newStatus });
            shopInfo.value.status = newStatus;
            uni.showToast({
              title: '已暂停营业',
              icon: 'none'
            });
          } catch (err) {
            // 失败时恢复switch状态
            shopStatus.value.checked = true;
            uni.showToast({ title: '状态更新失败', icon: 'none' });
          }
        }
      }
    });
  }
};

const navigateToBusinessHours = () => {
  uni.navigateTo({ url: '/pages/shop/business-hours' });
};
const navigateToDataAnalysis = () => {
  uni.navigateTo({ url: '/pages/data/analysis' });
};

// 获取公告列表
const fetchNoticeList = async () => {
  try {
    const {data} = await getNoticeList();
    // 显示所有公告
    noticeList.value = data || [];
  } catch (error) {
    console.error('获取公告列表失败:', error);
  }
};

// 格式化公告时间
const formatNoticeTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${month}-${day}`;
};

// 跳转到公告详情
const navigateToNoticeDetail = (noticeId) => {
  uni.navigateTo({
    url: `/pages/notice/detail?id=${noticeId}`
  });
};
onShow(async () => {
  const merchantId = getMerchantId();
  if (!merchantId) {
    uni.showToast({ title: '未获取到商家ID', icon: 'none' });
    return;
  }
  const { data } = await getMerchantInfo(merchantId);
  shopInfo.value = data || {};
  shopStatus.value.checked = data?.status === 1;
  // 请求接口获取经营数据概览
  const overviewResp = await getMerchantOverviewData(merchantId);
  if (overviewResp && overviewResp.data) {
    overviewData.value = overviewResp.data;
  }
  // 获取公告列表
  await fetchNoticeList();
});
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
}
.header {
  padding: 30rpx 0;
  text-align: center;
}
.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}
.card {
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.04);
  margin-bottom: 24rpx;
  padding: 24rpx 20rpx;
}
.overview-section {
  display: none;
}
.overview-card-list {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24rpx;
}
.overview-card {
  flex: 1;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.04);
  margin-right: 16rpx;
  padding: 32rpx 0 24rpx 0;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  &:last-child {
    margin-right: 0;
  }
}
.overview-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 8rpx;
}
.overview-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #ff6b6b;
  margin-top: 0;
}
.function-list {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  border-radius: 10rpx;
  margin-bottom: 24rpx;
}
.function-row {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 16rpx;
  margin-bottom: 24rpx;
}
.function-card {
  flex: 1;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.04);
  margin-right: 0;
  padding: 0;
  display: flex;
  align-items: stretch;
  min-height: 140rpx;
}
.function-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  border-bottom: none;
  transition: background-color 0.2s;
  background: transparent;
  border-radius: 16rpx;
  margin-right: 0;
  box-shadow: none;
}
.function-item-inner {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 140rpx;
}
.function-card:last-child {
  margin-right: 0;
}
.function-item {
  flex: 1;
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: none;
  transition: background-color 0.2s;
  background: transparent;
  border-radius: 16rpx;
  margin-right: 0;
  box-shadow: none;
  justify-content: flex-start;
}
.function-item:active {
  background-color: #f5f5f5;
}
.function-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 20rpx;
}
.function-text {
  flex: 1;
  font-size: 30rpx;
  color: #333;
}
.status-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}
.function-card {
  flex: 1;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.04);
  margin-right: 0;
  padding: 0;
  display: flex;
  align-items: stretch;
  min-height: 140rpx;
}
.function-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  border-bottom: none;
  transition: background-color 0.2s;
  background: transparent;
  border-radius: 16rpx;
  margin-right: 0;
  box-shadow: none;
}
.function-item-inner {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 140rpx;
}
.function-card:last-child {
  margin-right: 0;
}
.function-item {
  flex: 1;
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: none;
  transition: background-color 0.2s;
  background: transparent;
  border-radius: 16rpx;
  margin-right: 0;
  box-shadow: none;
  justify-content: flex-start;
}
.function-item:active {
  background-color: #f5f5f5;
}
.function-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 20rpx;
}
.function-text {
  flex: 1;
  font-size: 30rpx;
  color: #333;
}

/* 公告区域样式 */
.section-header {
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.notice-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.notice-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.2s;
}

.notice-item:last-child {
  border-bottom: none;
}

.notice-item:active {
  background-color: #f5f5f5;
}

.notice-title {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  margin-right: 20rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.notice-time {
  font-size: 24rpx;
  color: #999;
  flex-shrink: 0;
}

</style>